package com.ibangnuo.manage.service.employee;

import com.alibaba.fastjson.JSONObject;
import com.ibangnuo.framework.domain.Agent;
import com.ibangnuo.framework.domain.Employee;
import com.ibangnuo.framework.domain.User;
import com.ibangnuo.framework.domain.UserRole;
import com.ibangnuo.framework.domain.ext.AgentExt;
import com.ibangnuo.framework.domain.request.AgentQueryRequest;
import com.ibangnuo.framework.exception.ExceptionCast;
import com.ibangnuo.framework.model.response.*;
import com.ibangnuo.framework.utils.MD5Utils;
import com.ibangnuo.framework.utils.PrimaryKeyUtil;
import com.ibangnuo.manage.dao.UserRepository;
import com.ibangnuo.manage.dao.UserRoleRepository;
import com.ibangnuo.manage.dao.employee.AgentMapper;
import com.ibangnuo.manage.dao.employee.AgentRepository;
import com.ibangnuo.manage.dao.employee.EmployeeRepository;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Author:ly
 * @Data:2019/12/27 17:23
 * @Verdion:1.0
 */
@Transactional
@Service
public class AgentService {

    private static Logger LOGGER = LoggerFactory.getLogger(AgentService.class);
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private AgentRepository agentRepository;

    @Autowired
    private AgentMapper agentMapper;
    @Autowired
    private UserRoleRepository userRoleRepository;
    @Autowired
    private EmployeeRepository employeeRepository;

    /**
     * 查询公司名称
     *
     * @return
     */
    public QueryResponseResult query() {
//        List<Agent> all = agentRepository.findAll();
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        String loginUserId = user1.getId();
        Agent agent = null;

        QueryResult queryResult = new QueryResult();

        if (user1.getType() == 1) {//代理商
            agent = agentRepository.findByUserId(loginUserId);
            List<Agent> all = agentMapper.findAllcompanyName();
            queryResult.setList(all);
            return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
        }
        if (user1.getType() == 4) {//员工查询
            Employee byUserId1 = employeeRepository.findByUserId(user1.getId());
            if (byUserId1 != null) {
                String agent_id = byUserId1.getAgentId();
                Optional<Agent> byId = agentRepository.findById(agent_id);
                if (byId.isPresent()) {
                    agent = byId.get();

                }
            }
        }
        if (user1.getType() == 0) { //管理员
            agent.setId(null);
        }
        List<Agent> all = agentMapper.findAll(agent.getId());
        queryResult.setList(all);
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }


    /**
     * 分页查询
     *
     * @param agentQueryRequest
     * @return
     */
    public QueryResponseResult findList(AgentQueryRequest agentQueryRequest) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String id = user.getId();

        if (agentQueryRequest == null) {
            new AgentQueryRequest();
        }
        Agent agent = new Agent();
        if (StringUtils.isNotEmpty(agentQueryRequest.getCompanyName())) {
            agent.setCompanyName(agentQueryRequest.getCompanyName());
        }
        if (StringUtils.isNotEmpty(agentQueryRequest.getName())) {
            agent.setName(agentQueryRequest.getName());
        }
        if (agentQueryRequest.getPhone() != null) {
            agent.setPhone(agentQueryRequest.getPhone());
        }
        if (agentQueryRequest.getStatus() != null) {
            agent.setStatus(agentQueryRequest.getStatus());
        }
        if (StringUtils.isNotEmpty(agentQueryRequest.getNumber())) {
            agent.setNumber(agentQueryRequest.getNumber());
        }
        if (user.getType() == 0) {
            if (agentQueryRequest.getAgentIdAgentId() != null && agentQueryRequest.getAgentIdAgentId() != "") {
                agent.setParentId(agentQueryRequest.getAgentIdAgentId());
            } else {
                agent.setParentId("");
            }
        } else {
            Agent agent1 = agentRepository.findByUserId(id);
            agent.setParentId(agent1.getId());
        }
        agent.setIsDelete(1);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("companyName", ExampleMatcher.GenericPropertyMatchers.contains()).withIgnoreCase()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("number", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("phone", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("parentId", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("status", ExampleMatcher.GenericPropertyMatchers.exact())
                .withMatcher("isDelete", ExampleMatcher.GenericPropertyMatchers.exact());
        Example<? extends Agent> example = Example.of(agent, exampleMatcher);
        Sort sort = new Sort(Sort.Direction.DESC,"createTime");
        Pageable pageable = PageRequest.of(agentQueryRequest.getPage() - 1, agentQueryRequest.getLimit(),sort);
        Page<? extends Agent> all = agentRepository.findAll(example, pageable);
        QueryResult queryResult = new QueryResult();
        queryResult.setList(all.getContent());
        queryResult.setTotal(all.getTotalElements());
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }

    /**
     * 添加账号信息进入用户表
     * 添加代理商
     *
     * @param agentExt
     * @return
     */
    public ResponseResult add(AgentExt agentExt) {
        User byUsername = userRepository.findByUsername(agentExt.getUsername());
        if (byUsername != null) {
            return new ResponseResult(CommonCode.USERNAME_exist);
        }
        User user = new User();
        user.setCreateTime(new Date());
        user.setPassword(MD5Utils.md5(agentExt.getPassword(), "wang"));
        user.setUsername(agentExt.getUsername());
        user.setType(1);
        user.setStatus(0);//未授权
        user.setIsDelete(1);//未删除
        String agentExtJson = JSONObject.toJSONString(agentExt);
        Agent agent = JSONObject.parseObject(agentExtJson, Agent.class);
        User save = userRepository.save(user);
        agent.setUserId(save.getId());
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        //管理员添加代理商
        if (user1.getType() == 0) {
            if (agentExt.getAgentIdAgentId() != null && agentExt.getAgentIdAgentId() != "") {
                agent.setParentId(agentExt.getAgentIdAgentId());
            }
            agent.setParentId("0");
            agent.setHierarchy("1");
        } else {
            //代理商添加代理商
            Agent agent1 = agentRepository.findByUserId(user1.getId());
            agent.setParentId(agent1.getId());
            //判断当前登录代理商层级
            String agentHierarchy = "";
            String hierarchy = agent1.getHierarchy();
            if("1".equals(hierarchy)){
                //顶层代理，无需分割，后边加-2
                agentHierarchy = "1-2";
            }else{
                String[] hierarchyList = hierarchy.split("-");
                agentHierarchy = hierarchy + "-" + (Integer.parseInt(hierarchyList[hierarchyList.length-1])+1);
            }
            agent.setHierarchy(agentHierarchy);


        }

        agent.setStatus(0);
        agent.setIsDelete(1);
        agent.setUsername(agentExt.getUsername());
        agent.setCreateTime(new Date());
        agent.setNumber(String.valueOf(PrimaryKeyUtil.nextId()));
        agentRepository.save(agent);
        //添加关联表数据
        UserRole userRole = new UserRole();
        userRole.setCreateTime(new Date());
        userRole.setUserId(save.getId());
        userRole.setRoleId(agentExt.getRoleId());
        userRoleRepository.save(userRole);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public ObjectResult findById(String id) {
        Optional<Agent> optional = agentRepository.findById(id);
        if (optional.isPresent()) {
            return new ObjectResult(CommonCode.SUCCESS, optional.get());
        }
        return new ObjectResult(CommonCode.FAIL, false);
    }

    /**
     * 根据id修改
     *
     * @param id
     * @param agentExt
     * @return
     */
    public ResponseResult update(String id, AgentExt agentExt) {
        Agent one = this.getAgentById(id);
        User userById1 = this.getUserById(one.getUserId());
        if (one != null) {
            one.setStatus(agentExt.getStatus());
            one.setName(agentExt.getName());
            one.setPhone(agentExt.getPhone());
            one.setCompanyName(agentExt.getCompanyName());
            one.setCard(agentExt.getCard());
            one.setBank(agentExt.getBank());
            one.setBranch(agentExt.getBranch());
            one.setBankCardName(agentExt.getBankCardName());
            one.setBankCardNumber(agentExt.getBankCardNumber());
            one.setEmail(agentExt.getEmail());
            one.setAgentType(agentExt.getAgentType());
            one.setStatus(agentExt.getStatus());
            one.setRemark(agentExt.getRemark());
            one.setAgentScope(agentExt.getAgentScope());
            agentRepository.save(one);
            userById1.setStatus(agentExt.getStatus());
            if (StringUtils.isNotEmpty(agentExt.getPassword())) {
                User userById = this.getUserById(one.getUserId());
                if (userById == null) {
                    ExceptionCast.cast(CommonCode.SERVER_ERROR);
                }
                userById.setPassword(MD5Utils.md5(agentExt.getPassword(), "wang"));
                userRepository.save(userById);
            }
            return new ResponseResult(CommonCode.SUCCESS);
        }
        return new ResponseResult(CommonCode.FAIL);
    }

    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    public ResponseResult delete(String id) {
        Agent one = this.getAgentById(id);
        User userOne = this.getUserById(one.getUserId());
        one.setIsDelete(0);
        userOne.setIsDelete(0);
        agentRepository.save(one);
        userRepository.save(userOne);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 查询全部代理商
     * @return
     */
    public ObjectResult findAll(){
        //List<Agent> all = agentRepository.findAll();
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String id = user.getId();
        Agent agent = agentRepository.findByUserId(id);
        List<Agent> agentList = agentRepository.findByParentIdAndIsDelete(agent.getId(), 1);
        agentList.add(agent);
        return new ObjectResult(CommonCode.SUCCESS,agentList);
    }

    /**
     * 代理商统计
     * @return
     */
    public ObjectResult statistic(){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String id = user.getId();
        long count1 = 0;
        long count2 = 0;
        Agent agent = agentRepository.findByUserId(id);
        List<Agent> agentList1 = agentRepository.findByParentIdAndIsDelete(agent.getId(), 1);
        count1 = agentList1.size();
        for (Agent agent1 : agentList1) {
            List<Agent> agentList2 = agentRepository.findByParentIdAndIsDelete(agent1.getId(), 1);
            count2 = count2 = agentList2.size();
        }
        Map<String,Object> map = new HashMap<>();
        map.put("count1",count1);
        map.put("count2",count2);
        return new ObjectResult(CommonCode.SUCCESS,map);

    }

    /**
     * 查找自己与旗下的代理商
     * @param id
     * @return
     */
    public ObjectResult findByParentIdAndMySelf(String id){
        List<Agent> agentList = agentRepository.findByParentIdAndIsDelete(id, 1);
        Agent agent = this.getAgentById(id);
        agentList.add(agent);
        return new ObjectResult(CommonCode.SUCCESS,agentList);
    }

    /**
     * 根据id查找
     *
     * @return
     */
    private Agent getAgentById(String id) {
        Optional<Agent> optional = agentRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * 根据id获取用户
     *
     * @param id
     * @return
     */
    private User getUserById(String id) {
        Optional<User> optional = userRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * 当前登录人代理商
     * @return
     */
    public ObjectResult findAgent(){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        Agent agent = agentRepository.findByUserId(user.getId());
        return new ObjectResult(CommonCode.SUCCESS,agent);
    }




}
